from rest_framework import serializers
from django.utils import timezone
from datetime import datetime, timedelta
from typing import Dict, Any, List


class AnalyticsDataSerializer(serializers.Serializer):
    """
    分析数据序列化器
    """
    stats = serializers.DictField(help_text="基础统计数据")
    file_type_distribution = serializers.ListField(
        child=serializers.DictField(),
        help_text="文件类型分布"
    )
    task_status_distribution = serializers.ListField(
        child=serializers.DictField(),
        help_text="任务状态分布"
    )
    recent_activity = serializers.DictField(help_text="最近活动统计")
    performance_metrics = serializers.DictField(help_text="性能指标")


class UsageStatisticsSerializer(serializers.Serializer):
    """
    使用统计序列化器
    """
    trends = serializers.ListField(
        child=serializers.DictField(),
        help_text="使用趋势数据"
    )
    period = serializers.CharField(help_text="统计周期")
    
    def validate_trends(self, value):
        """
        验证趋势数据格式
        """
        required_fields = ['date', 'files_uploaded', 'tasks_created', 'tasks_completed']
        
        for item in value:
            for field in required_fields:
                if field not in item:
                    raise serializers.ValidationError(
                        f"趋势数据缺少必需字段: {field}"
                    )
        
        return value


class PerformanceMetricsSerializer(serializers.Serializer):
    """
    性能指标序列化器
    """
    avg_processing_time = serializers.FloatField(
        help_text="平均处理时间（秒）"
    )
    success_rate = serializers.FloatField(
        help_text="成功率（百分比）"
    )
    error_rate = serializers.FloatField(
        help_text="错误率（百分比）"
    )
    total_processed = serializers.IntegerField(
        help_text="总处理数量"
    )
    
    def validate_success_rate(self, value):
        """
        验证成功率
        """
        if not 0 <= value <= 100:
            raise serializers.ValidationError("成功率必须在0-100之间")
        return value
    
    def validate_error_rate(self, value):
        """
        验证错误率
        """
        if not 0 <= value <= 100:
            raise serializers.ValidationError("错误率必须在0-100之间")
        return value


class LogAnalysisSerializer(serializers.Serializer):
    """
    日志分析序列化器
    """
    level_distribution = serializers.ListField(
        child=serializers.DictField(),
        help_text="日志级别分布"
    )
    hourly_trends = serializers.ListField(
        child=serializers.DictField(),
        help_text="按小时统计趋势"
    )
    recent_errors = serializers.ListField(
        child=serializers.DictField(),
        help_text="最近错误日志"
    )
    total_logs = serializers.IntegerField(help_text="总日志数量")


class TemplateUsageSerializer(serializers.Serializer):
    """
    模板使用统计序列化器
    """
    id = serializers.IntegerField(help_text="模板ID")
    name = serializers.CharField(help_text="模板名称")
    usage_count = serializers.IntegerField(help_text="使用次数")
    file_count = serializers.IntegerField(help_text="关联文件数")
    created_at = serializers.CharField(help_text="创建时间")
    is_active = serializers.BooleanField(help_text="是否激活")


class FileStatisticsSerializer(serializers.Serializer):
    """
    文件统计序列化器
    """
    total_size = serializers.IntegerField(help_text="总文件大小（字节）")
    total_size_formatted = serializers.CharField(help_text="格式化的总文件大小")
    file_count = serializers.IntegerField(help_text="文件总数")
    extension_distribution = serializers.DictField(
        help_text="文件扩展名分布"
    )
    template_file_distribution = serializers.ListField(
        child=serializers.DictField(),
        help_text="按模板分组的文件分布"
    )


class DashboardStatsSerializer(serializers.Serializer):
    """
    仪表板统计序列化器
    """
    total_files = serializers.IntegerField(help_text="总文件数")
    total_tasks = serializers.IntegerField(help_text="总任务数")
    total_templates = serializers.IntegerField(help_text="总模板数")
    active_templates = serializers.IntegerField(help_text="活跃模板数")
    
    recent_activity = serializers.DictField(help_text="最近活动")
    task_status = serializers.DictField(help_text="任务状态分布")


class LogEntrySerializer(serializers.Serializer):
    """
    日志条目序列化器
    """
    id = serializers.IntegerField(help_text="日志ID")
    level = serializers.CharField(help_text="日志级别")
    message = serializers.CharField(help_text="日志消息")
    module = serializers.CharField(help_text="模块名称")
    created_at = serializers.CharField(help_text="创建时间")
    details = serializers.CharField(
        allow_null=True,
        help_text="详细信息"
    )


class AnalyticsQuerySerializer(serializers.Serializer):
    """
    分析查询参数序列化器
    """
    start_date = serializers.DateField(
        required=False,
        help_text="开始日期"
    )
    end_date = serializers.DateField(
        required=False,
        help_text="结束日期"
    )
    days = serializers.IntegerField(
        default=30,
        min_value=1,
        max_value=365,
        help_text="统计天数"
    )
    hours = serializers.IntegerField(
        default=24,
        min_value=1,
        max_value=168,  # 7天
        help_text="统计小时数"
    )
    level = serializers.ChoiceField(
        choices=[
            ('', '全部'),
            ('DEBUG', '调试'),
            ('INFO', '信息'),
            ('WARNING', '警告'),
            ('ERROR', '错误'),
            ('CRITICAL', '严重错误')
        ],
        required=False,
        allow_blank=True,
        help_text="日志级别"
    )
    
    def validate(self, attrs):
        """
        交叉验证
        """
        start_date = attrs.get('start_date')
        end_date = attrs.get('end_date')
        
        if start_date and end_date:
            if start_date > end_date:
                raise serializers.ValidationError(
                    "开始日期不能晚于结束日期"
                )
            
            # 检查日期范围是否合理
            date_diff = (end_date - start_date).days
            if date_diff > 365:
                raise serializers.ValidationError(
                    "日期范围不能超过365天"
                )
        
        return attrs


class TrendDataSerializer(serializers.Serializer):
    """
    趋势数据序列化器
    """
    date = serializers.CharField(help_text="日期")
    files_uploaded = serializers.IntegerField(help_text="上传文件数")
    tasks_created = serializers.IntegerField(help_text="创建任务数")
    tasks_completed = serializers.IntegerField(help_text="完成任务数")
    
    def validate_date(self, value):
        """
        验证日期格式
        """
        try:
            datetime.strptime(value, '%Y-%m-%d')
        except ValueError:
            raise serializers.ValidationError(
                "日期格式必须为 YYYY-MM-DD"
            )
        return value


class SystemHealthSerializer(serializers.Serializer):
    """
    系统健康状态序列化器
    """
    status = serializers.ChoiceField(
        choices=[
            ('healthy', '健康'),
            ('warning', '警告'),
            ('critical', '严重')
        ],
        help_text="系统状态"
    )
    
    cpu_usage = serializers.FloatField(
        min_value=0,
        max_value=100,
        help_text="CPU使用率（百分比）"
    )
    
    memory_usage = serializers.FloatField(
        min_value=0,
        max_value=100,
        help_text="内存使用率（百分比）"
    )
    
    disk_usage = serializers.FloatField(
        min_value=0,
        max_value=100,
        help_text="磁盘使用率（百分比）"
    )
    
    active_connections = serializers.IntegerField(
        min_value=0,
        help_text="活跃连接数"
    )
    
    response_time = serializers.FloatField(
        min_value=0,
        help_text="平均响应时间（毫秒）"
    )
    
    error_count = serializers.IntegerField(
        min_value=0,
        help_text="错误数量"
    )
    
    last_check = serializers.DateTimeField(help_text="最后检查时间")


class ExportDataSerializer(serializers.Serializer):
    """
    数据导出序列化器
    """
    data_type = serializers.ChoiceField(
        choices=[
            ('analytics', '分析数据'),
            ('logs', '日志数据'),
            ('files', '文件数据'),
            ('tasks', '任务数据'),
            ('templates', '模板数据')
        ],
        help_text="数据类型"
    )
    
    format = serializers.ChoiceField(
        choices=[
            ('csv', 'CSV'),
            ('excel', 'Excel'),
            ('json', 'JSON')
        ],
        default='csv',
        help_text="导出格式"
    )
    
    start_date = serializers.DateField(
        required=False,
        help_text="开始日期"
    )
    
    end_date = serializers.DateField(
        required=False,
        help_text="结束日期"
    )
    
    filters = serializers.DictField(
        required=False,
        default=dict,
        help_text="过滤条件"
    )
    
    def validate(self, attrs):
        """
        交叉验证
        """
        start_date = attrs.get('start_date')
        end_date = attrs.get('end_date')
        
        if start_date and end_date and start_date > end_date:
            raise serializers.ValidationError(
                "开始日期不能晚于结束日期"
            )
        
        return attrs


class ReportConfigSerializer(serializers.Serializer):
    """
    报告配置序列化器
    """
    report_type = serializers.ChoiceField(
        choices=[
            ('daily', '日报'),
            ('weekly', '周报'),
            ('monthly', '月报'),
            ('custom', '自定义')
        ],
        help_text="报告类型"
    )
    
    include_charts = serializers.BooleanField(
        default=True,
        help_text="是否包含图表"
    )
    
    include_details = serializers.BooleanField(
        default=False,
        help_text="是否包含详细数据"
    )
    
    email_recipients = serializers.ListField(
        child=serializers.EmailField(),
        required=False,
        help_text="邮件接收者列表"
    )
    
    schedule_enabled = serializers.BooleanField(
        default=False,
        help_text="是否启用定时发送"
    )
    
    schedule_time = serializers.TimeField(
        required=False,
        help_text="定时发送时间"
    )